﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using GameSchool.Models.Repositories;
using GameSchool.Models.ViewModels;
using GameSchool.Models.Interfaces;
using GameSchool.Models;

namespace GameSchool.Controllers
{
    public class QuizController : Controller
    {
        //
        // GET: /Quiz/

        public ActionResult Index()
        {
            QuizRepository rep = new QuizRepository();
            var quizes = rep.GetQuiz().Take(10);

            return View(quizes);
        }

        public ActionResult DeleteQuiz()
        {
            QuizRepository rep = new QuizRepository();

            rep.DeleteQuiz(6);
            rep.Save();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Create(int? ID)
        {
            //Make sure we have the course ID
            if (ID == null)
                throw new ArgumentNullException("Quiz Create - null passed as parameter");

            //Make sure that the user is teaching this course
            var userID = (Guid)Membership.GetUser().ProviderUserKey;
            var db = new GameSchoolDBDataContext();

            var isTeacher = (from u in db.IsInCourses
                             where u.UserID == userID && u.CourseID == ID
                             select u.IsTeacher).SingleOrDefault();

            //If the user isn't a teacher (!= true because it might be null) nor an admin we throw him to his homepage.
            if (isTeacher != true && !(User.IsInRole("Admin")))
                RedirectToAction("Index", "Home");

            var q = new Quiz();
            q.LevelID = ID;
            q.CourseID = (from l in db.Levels
                          where l.ID == ID
                          select l.CourseID).SingleOrDefault();
                                  

            return View(q);
        }
        [HttpPost]
        public ActionResult Create(Quiz q)
        {
            //Need to errorcheck this.

            //Setting the author of the quiz..
            q.Author = (Guid)Membership.GetUser().ProviderUserKey;

            //Hooking into the Repos
            var assignmentRep = new AssignmentRepository();
            var quizRep = new QuizRepository();
            q.DatePub = DateTime.Now;
            //Saving the quiz
            quizRep.AddQuiz(q);
            quizRep.Save();

            //Creating a row in the Assignment table 
            Assignment newAssignment = new Assignment();
            newAssignment.ResourceID = q.ID;
            newAssignment.AssignmentType = "Quiz";
           
            newAssignment.CourseID = q.CourseID;
            newAssignment.LevelID = q.LevelID;
            assignmentRep.AddAssignment(newAssignment);
            assignmentRep.Save();
            
            //Passing the ID of the quiz along to the next view ..
            Session["QuizSessionID"] = q.ID; 
            //Redirect the user to the CreateQuestion view so he can add questions to the newly created quiz ..
            return RedirectToAction("CreateQuestion", "Quiz");
        }

        public ActionResult CreateQuestion()
        {

            //Just a selectList to change Bonus Points answer possibilities to Icelandic.s
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem 
            {
                Text = "Nei",
                Value = "False",
                Selected = true
            });
            items.Add(new SelectListItem
            {
                Text = "Já",
                Value = "True"
            });  
            ViewBag.GivesBonus = items;

            return View();
        }

        public ActionResult Choices()
        {
            //Just a selectList to change Bonus Points answer possibilities to Icelandic.s
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem
            {
                Text = "Nei",
                Value = "False",
                Selected = true
            });
            items.Add(new SelectListItem
            {
                Text = "Já",
                Value = "True"
            });
            ViewBag.CorrectAnswer = items;

            return View();
        }

        /* Not used anymore - Should be merged into the Create() above 
        [HttpPost]
        public ActionResult CreateQuiz(Quiz newQuiz, Assignment newAssignment)
        {
            AssignmentRepository rep = new AssignmentRepository();
            QuizRepository repository = new QuizRepository();
            newQuiz.Author = (Guid)Membership.GetUser().ProviderUserKey;
            repository.AddQuiz(newQuiz);
            repository.Save();

            Session["QuizSessionID"] = newQuiz.ID; 

            newAssignment.ResourceID = newQuiz.ID;
            newAssignment.AssignmentType = "Quiz";
            newAssignment.CourseID = newQuiz.CourseID;
            newAssignment.LevelID = 1;
            rep.AddAssignment(newAssignment);
            rep.Save();

            return RedirectToAction("CreateQuestion", "Quiz");
        }
        */ 
        
        [HttpPost]
        public ActionResult CreateQuestion(Question newQuestion)
        {
            QuizRepository repository = new QuizRepository();
            newQuestion.QuizID = (int)Session["QuizSessionID"]; 
            repository.AddQuestion(newQuestion);
            repository.Save();
            Session["QuizQuestionID"] = newQuestion.ID;

            return RedirectToAction("Choices", "Quiz");
        }
        [HttpPost]
        public ActionResult Choices(FormCollection formData)
        {

            //Creating the models we'll be plocking the data from the form into..
            Choice newChoice = new Choice();

            //First we plock into the choice model, since we'll always be creating a new choice..
            QuizRepository repository = new QuizRepository();
            newChoice.QuestionID = (int)Session["QuizQuestionID"];

            //This is important - defines wether the choice is actually the correct choice
            newChoice.Correct = Convert.ToBoolean(formData["CorrectAnswer"]);
            newChoice.Title = formData["Title"];

            //Save the choice
            repository.AddChoice(newChoice);
            repository.Save();

            //I guess this part is put here so that we'll be able to create another choice form .. ? Oli should know.
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem
            {
                Text = "Nei",
                Value = "False",
                Selected = true
            });
            items.Add(new SelectListItem
            {
                Text = "Já",
                Value = "True"
            });
            ViewBag.CorrectAnswer = items;
            return RedirectToAction("Choices", "Quiz");

        }

        //Only works when I send in the ID of the quiz manually (for now)
        public ActionResult Display(int? ID)
        {
            GameSchoolDBDataContext db = new GameSchoolDBDataContext();
            PointsRepository prep = new PointsRepository();
            QuizRepository quiz = new QuizRepository();
            Guid guid = new Guid();
            guid = (Guid)Membership.GetUser().ProviderUserKey;
            var getQuiz = quiz.GetQuizByID(ID);

            var getQuestions = quiz.GetQuestionsByQuizID(ID);
            bool comp;
            int assignmentId = (from v in db.Quizs
                                from d in db.Assignments
                                where v.ID == d.ResourceID
                                where v.ID == ID
                                where d.AssignmentType == "Quiz"
                                select d.ID).SingleOrDefault();
            var completed = prep.GetAssignmentPoints(assignmentId, guid);
            if (!(completed == null))
            {
                comp = true;
            }
            else
            {
                comp = false;
            }
            //Viewmodel stuff

            //Creates a list of QuizViewModels to load everything into later
            List<QuizViewModel> quizview = new List<QuizViewModel>();
           
            //Create a new ViewModel for each question
            foreach (var q in getQuestions)
            {
                
                QuizViewModel model = new QuizViewModel();
                model.QuestionTitle = q.Title;
                model.QuestionID = q.ID;
                model.completed = comp;
                model.quizID = ID;
                model.questionHint = q.Hint;
                model.courseID = (from quizes in db.Quizs
                                  where q.QuizID == quizes.ID
                                  select quizes.CourseID).SingleOrDefault();

                model.choices  = new List<QuizViewModel>();
                
                // Fetch choices for each question
                var getChoices = quiz.GetChoicesByQuestionID(q.ID);
               
                
                //Load each choice into a list of choices, one list of choices per question.
                foreach (var c in getChoices)
                {
                    QuizViewModel ble = new QuizViewModel();
                    ble.Correct = c.Correct;
                    ble.ID = c.ID;
                    ble.QuestionID = c.QuestionID;
                    ble.completed = comp;
                    ble.Title = c.Title;
                    model.choices.Add(ble);
                    
                    
                }
                

                //Send choice list into the ViewModel
                

                //Send question list into the list of QuizViewModels we created earlier.
                quizview.Add(model); 
            }
            ViewData["list"] = quizview;
            ViewData["id"] = ID;
            ViewData["testTitle"] = getQuiz.Name;
            ViewData["courseID"] = getQuiz.CourseID;
           
            return View();
        }
        
        [HttpPost]
        public ActionResult Display(FormCollection formData)
        {
            var db = new GameSchoolDBDataContext();
            QuizRepository userquiz = new QuizRepository();
            AssignmentScore ascore = new AssignmentScore();
            PointsRepository prep = new PointsRepository();
            UserQuiz c = new UserQuiz();
            Guid guid = new Guid();
            // Gets the current userID of the logged on user
            guid = (Guid)Membership.GetUser().ProviderUserKey;
            
            // gets the assignmentid from the form that was posted.
            var assignmentid = Request.Form["ID"];
            var quizid = Convert.ToInt32(assignmentid);
            // gets the quiz and questions from the quizid 
            var getQuiz = userquiz.GetQuizByID(quizid);
            var getQuestions = userquiz.GetQuestionsByQuizID(quizid);
      
            int points = 0;
            int questions = 0;
            foreach (Question q in getQuestions)
            {
                var getChoices = userquiz.GetChoicesByQuestionID(q.ID);
                var studentPick = Request.Form[q.ID.ToString()];
                int choice = Convert.ToInt32(studentPick);
                foreach (var cho in getChoices)
                {
                    if (cho.Correct == true)
                        if (choice == cho.ID)
                            points = points + 1;
                }
                questions = questions +1 ;
                            
            }

           // Þetta ætti að skila value-inu á þeim radio takka sem notandinn valdi í þessari spurningu.


            
            ascore.UserID = guid;
            

            ascore.Bonuspoints = 0;
           
            
            if (points == 0)
            {
                ascore.Points=0;
                
            }
            else 
            {
                double ble = (double)points/(double)questions;
                double ble2 = ble*getQuiz.MaxPoints;
                ascore.Points = (int)ble2;
            }



            int assignmentId = (from v in db.Quizs
                                from d in db.Assignments
                                where v.ID == d.ResourceID
                                where v.ID == quizid
                                where d.AssignmentType == "Quiz"
                                select d.ID).SingleOrDefault();
            ascore.AssignmentID = assignmentId;
            var completed = prep.GetAssignmentPoints(assignmentId, guid);

                if(completed ==null)
                {
                prep.AddPoints(ascore);
                prep.Save();
                }
            
           

          
            
            return RedirectToAction("Index", "Home");
        }
    }
}
